﻿using Dapper;
using System;
using BCEntity.Trading.Purchase.GoodsPurchaseChecklist;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.Purchase.GoodsPurchaseChecklist
{
    /// <summary>
    /// 商品采购清单
    /// </summary>
    public class GoodsPurchaseChecklistData : IGoodsPurchaseChecklistData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM goodspurchasechecklist";
        private const string QUERY = @"SELECT GoodsPurchaseChecklistId,GoodsPurchaseNo,NormName,NormNo,VendorCategoryId,VendorCategoryName,VendorId,VendorName,PurchaseCount,PurchaseUnit,
                                            PurchasePrice,TaxRate,GoodsPurchaseId,TaxAmount,PurchaseAmount,CreateAdminId,CreateAdminName,CreateTime,UpdateTime,EditAdminId,StorageCount,
                                            EditAdminName,GoodsPurchaseItemId,SaleGoodsCategoryId,CategoryName,SaleGoodsId,GoodsName,SKU,SaleGoodsNormId,InventoryStatus,InventoryStatusStr
                                        FROM goodspurchasechecklist";
        public GoodsPurchaseChecklistData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查商品采购清单是否存在
        public async Task<bool> Exists(long goodsPurchaseChecklistId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseChecklistId=?GoodsPurchaseChecklistId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseChecklistId", goodsPurchaseChecklistId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 该记录是否存在此采购项
        public async Task<bool> PurchaseItemExists(long goodsPurchaseItemId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseItemId=?GoodsPurchaseItemId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseItemId", goodsPurchaseItemId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加商品采购清单
        public async Task<GoodsPurchaseChecklistEntity> Add(GoodsPurchaseChecklistEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("goodspurchasechecklist", new string[] { "GoodsPurchaseNo","NormName", "NormNo", "VendorCategoryId", "VendorCategoryName", "VendorId", "VendorName",
                "PurchaseCount", "PurchaseUnit", "PurchasePrice", "GoodsPurchaseId", "PurchaseAmount", "CreateAdminId", "CreateAdminName", "GoodsPurchaseItemId",
                "SaleGoodsCategoryId", "CategoryName", "SaleGoodsId", "GoodsName", "SKU", "SaleGoodsNormId","TaxRate", "TaxAmount" });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseChecklistId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseNo", entity.GoodsPurchaseNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?VendorCategoryId", entity.VendorCategoryId, DbType.Int32, size: 11);
            parameters.Add("?VendorCategoryName", entity.VendorCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?VendorId", entity.VendorId, DbType.Int32, size: 11);
            parameters.Add("?VendorName", entity.VendorName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PurchaseCount", entity.PurchaseCount, DbType.Int32, size: 11);
            parameters.Add("?PurchaseUnit", entity.PurchaseUnit?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?PurchasePrice", entity.PurchasePrice, DbType.Decimal, size: 16);
            parameters.Add("?GoodsPurchaseId", entity.GoodsPurchaseId, DbType.Int64, size: 20);
            parameters.Add("?TaxRate", entity.TaxRate, DbType.Decimal, size: 10);
            parameters.Add("?TaxAmount", entity.TaxAmount, DbType.Decimal, size: 16);
            parameters.Add("?PurchaseAmount", entity.PurchaseAmount, DbType.Decimal, size: 16);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?GoodsPurchaseItemId", entity.GoodsPurchaseItemId, DbType.Int64, size: 20);
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SaleGoodsNormId", entity.SaleGoodsNormId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseChecklistEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改商品采购清单
        public async Task<GoodsPurchaseChecklistEntity> Update(GoodsPurchaseChecklistEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("goodspurchasechecklist", new string[] { "NormName", "NormNo", "VendorCategoryId", "VendorCategoryName", "VendorId", "VendorName",
                "PurchaseCount", "PurchaseUnit", "PurchasePrice", "TaxRate", "GoodsPurchaseId", "TaxAmount", "PurchaseAmount", 
                "EditAdminId", "EditAdminName", "GoodsPurchaseItemId", "SaleGoodsCategoryId", "CategoryName", "SaleGoodsId", "GoodsName", "SKU", "SaleGoodsNormId" }
                , new string[] { "GoodsPurchaseChecklistId" });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseChecklistId=?GoodsPurchaseChecklistId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseChecklistId", entity.GoodsPurchaseChecklistId, DbType.Int64, size: 20);
            parameters.Add("?GoodsPurchaseNo", entity.GoodsPurchaseNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?VendorCategoryId", entity.VendorCategoryId, DbType.Int32, size: 11);
            parameters.Add("?VendorCategoryName", entity.VendorCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?VendorId", entity.VendorId, DbType.Int32, size: 11);
            parameters.Add("?VendorName", entity.VendorName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PurchaseCount", entity.PurchaseCount, DbType.Int32, size: 11);
            parameters.Add("?PurchaseUnit", entity.PurchaseUnit?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?PurchasePrice", entity.PurchasePrice, DbType.Decimal, size: 16);
            parameters.Add("?TaxRate", entity.TaxRate, DbType.Decimal, size: 10);
            parameters.Add("?GoodsPurchaseId", entity.GoodsPurchaseId, DbType.Int64, size: 20);
            parameters.Add("?TaxAmount", entity.TaxAmount, DbType.Decimal, size: 16);
            parameters.Add("?PurchaseAmount", entity.PurchaseAmount, DbType.Decimal, size: 16);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?GoodsPurchaseItemId", entity.GoodsPurchaseItemId, DbType.Int64, size: 20);
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SaleGoodsNormId", entity.SaleGoodsNormId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseChecklistEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除商品采购清单
        public async Task<bool> Delete(long goodsPurchaseChecklistId)
        {
            string sql = @"DELETE FROM goodspurchasechecklist WHERE GoodsPurchaseChecklistId=?GoodsPurchaseChecklistId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseChecklistId", goodsPurchaseChecklistId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取商品采购清单
        public async Task<GoodsPurchaseChecklistEntity> GetEntity(long goodsPurchaseChecklistId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseChecklistId=?GoodsPurchaseChecklistId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseChecklistId", goodsPurchaseChecklistId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<GoodsPurchaseChecklistEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购清单列表
        public async Task<IEnumerable<GoodsPurchaseChecklistEntity>> GetList(long goodsPurchaseId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseId=?GoodsPurchaseId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseId", goodsPurchaseId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<GoodsPurchaseChecklistEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购清单分页
        public async Task<(IEnumerable<GoodsPurchaseChecklistEntity>, int)> Query(long? goodsPurchaseId, string categoryName, string goodsName, string sku, string vendorName,
            string adminName, long? adminId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(categoryName))
            {
                wheres.Add("CategoryName LIKE CONCAT('%',CONCAT(?CategoryName,'%'))");
                parameters.Add("?CategoryName", categoryName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(goodsName))
            {
                wheres.Add("GoodsName LIKE CONCAT('%',CONCAT(?GoodsName,'%'))");
                parameters.Add("?GoodsName", goodsName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(sku))
            {
                wheres.Add("SKU LIKE CONCAT('%',CONCAT(?SKU,'%'))");
                parameters.Add("?SKU", sku?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(vendorName))
            {
                wheres.Add("VendorName LIKE CONCAT('%',CONCAT(?VendorName,'%'))");
                parameters.Add("?VendorName", vendorName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(adminName))
            {
                wheres.Add("CreateAdminName LIKE CONCAT('%',CONCAT(?CreateAdminName,'%'))");
                parameters.Add("?CreateAdminName", adminName?.Trim(), DbType.AnsiString);
            }
            if (adminId.HasValue)
            {
                wheres.Add("CreateAdminId=?CreateAdminId");
                parameters.Add("?CreateAdminId", adminId.Value, DbType.Int64);
            }
            if (goodsPurchaseId.HasValue)
            {
                wheres.Add("GoodsPurchaseId=?GoodsPurchaseId");
                parameters.Add("?GoodsPurchaseId", goodsPurchaseId.Value, DbType.Int64);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM goodspurchasechecklist {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<GoodsPurchaseChecklistEntity, int>(sql, parameters);
        }
        #endregion
    }
}



